import axios from 'axios'
import { Message } from 'element-ui'
import { getLoginAuthentication, removeAllLoginInfo } from '@/utils/userToken';

// 创建一个 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000,
  headers:{
    'Content-Type':"application/json;charset=uft-8"
  },
  withCredentials:true,// 允许跨域
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = getLoginAuthentication();
    if (token) {
      // 携带认证请求头
      config.headers['Authentication'] = token;
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 文件下载时
    if (response.data.code === undefined){
      return response;
    }

    if (response.status !== 200) {
      Message({
        message: '系统异常',
        type: 'error',
        duration: 2 * 1000
      })
    }

    const responseData = response.data;
    if (responseData.code === 104 || responseData.code === 105) {
      // 无效的登录token 删除所有的登录信息
      removeAllLoginInfo();
      Message({
        message: responseData.message,
        type: 'error',
        duration: 2 * 1000
      })
      window.open('http://localhost:9528/#/login', '_self');
      return Promise.reject(responseData.message)
    }

    return responseData;
  },
  error => {
    Message({
      message: "系统异常，请稍后再试！",
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)
export default service
